package com.healthysys.backend.controller;

import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api") // 确保这个前缀存在
public class CaptchaController {

    private final RedisTemplate<String, String> redisTemplate;

    public CaptchaController(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @GetMapping("/captcha")
    public void getCaptcha(@RequestParam String uuid, HttpServletResponse response) throws IOException {
        try {
            System.out.println("接收到验证码请求，UUID: " + uuid);

            // 设置响应头
            response.setContentType("image/png");
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
            response.addHeader("Cache-Control", "post-check=0, pre-check=0");
            response.setDateHeader("Expires", 0);
            response.setHeader("Access-Control-Allow-Origin", "http://localhost:5173");
            response.setHeader("Access-Control-Allow-Credentials", "true");

            // 生成验证码图片
            SpecCaptcha captcha = new SpecCaptcha(130, 48, 5);
            captcha.setCharType(Captcha.TYPE_DEFAULT);

            // 存储验证码
            String code = captcha.text();
            System.out.println("生成验证码: " + code + " for UUID: " + uuid);
            redisTemplate.opsForValue().set("captcha:" + uuid, code, 5, TimeUnit.MINUTES);

            // 写入响应
            captcha.out(response.getOutputStream());
            System.out.println("成功发送验证码图片");
        } catch (Exception e) {
            System.err.println("验证码生成失败: " + e.getMessage());
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Captcha generation failed: " + e.getMessage());
            e.printStackTrace();
        }
    }
}